<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Pro;
use App\Att;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Bid;
use Auth;
use DB;
use Validator;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Session;

class ProController extends Controller
{
    protected $middleware = ['App\Http\Middleware\Authenticate'=>[]];


    //借款页面
    public function jie() {
    	return view('woyaojiekuan');
    }



    //借款数据提交
    public function jiePost(Request $req) {
        /*自动验证*/
        // $this->validate($req,[
        //     'age'=>'required | in:15,40,80',
        //     'money'=>'required | numeric | digits_between:3,7',
        //     'mobile'=>'required | regex:/1[3578]{9}/'
        // ],
        // [   
        //     'age.required'=>':attribute 必须填写',
        //     'in'=>':attribute 不在范围内',
        //     'money.required'=>'金额必须填写',
        //     'numeric'=>'金额必须是数字',
        //     'digits_between'=>'请在范围内选择要借的钱',
        //     'mobile.required'=>'手机号必须填写',
        //     'regex'=>'手机号必须是11位,且必须是现有的号段'
        // ]);

        /*手动验证*/
        $validator = Validator::make($req->all(),[
            'age'=>'required | in:15,40,80',
            'money'=>'required | numeric | digits_between:3,7',
            'mobile'=>'required | regex:/1[3578]{9}/'
        ],
        [   
            'age.required'=>':attribute 必须填写',
            'in'=>':attribute 不在范围内',
            'money.required'=>'金额必须填写',
            'numeric'=>'金额必须是数字',
            'digits_between'=>'请在范围内选择要借的钱',
            'mobile.required'=>'手机号必须填写',
            'regex'=>'手机号必须是11位,且必须是现有的号段'
        ]);

        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        /*验证码*/
        if(strtoupper($req->imgcode) !== $req->session()->get('code')) {
            return back()->with('msg','验证码不正确');
        }


    	$pro = new Pro();
    	$att = new Att();
    	$user = $req->user();

    	//主表
    	$pro->uid = $user->uid;
    	$pro->name = $user->name;
    	$pro->money = $req->money*100;
    	$pro->mobile = $req->mobile;
    	$pro->pubtime = time();
    	$pro->save();

    	//附表
    	$att->uid = $user->uid;
    	$att->age = $req->age;
    	$att->pid = $pro->pid;
    	$att->save();
    	return '借款成功';
    }



    //投标
    public function pro($pid) {
        $pro = Pro::where(['pid'=>$pid,'status'=>1])->first();
        // dd($pro);
        return view('lijitouzi',['pro'=>$pro]);
    }



    //投资
    public function touziPost(Request $req,$pid) {
        // dd($req->all());
        /*获取用户的信息*/
        $pro = Pro::find($pid);
        $bid = new Bid();
        $user = Auth::user();  //获取用户信息的
        // dd($user);

        /*修复小BUG*/
        if($req->v_amount == 0) {
            return "投资金额不能为0!!!";
        }


        /*判断,在投资过程中,数据是否被篡改*/
        $md5 = $req->v_oid.$req->v_pstatus.$req->v_amount.$req->v_moneytype.'%()#QOKFDLS:1*&U';
        $md5 = strtoupper(md5($md5));
        if($md5 !== $req->v_md5str) {
            return '数据被篡改!!!';
        }

        // 写入投资表bids
        $bid->uid = $user->uid;//用户uid
        $bid->pid = $pid;   //项目pid
        $bid->title = $pro->title; //项目名称
        $bid->money = $req->v_amount*100;//投标金额
        $bid->pubtime = time(); //投标时间

        //把数据写入数据库
        $bid->save();

        //用户投资的钱写入项目表projects
        $pro->recive += $bid->money;
        $pro->save();

        //判断,投资完成后
        if($pro->recive == $pro->money) {
            $this->touziDone($pid);
        }
        return "购买成功";
    }



    /*项目投资完成,修改状态*/
    public function touziDone($pid) {
        /**
        * 1. 修改项目的状态
        * status = 2,还款收益中
        */
        $pro = Pro::find($pid);
        $pro->status = 2;
        $pro->save();
        /**
        * 2. 为借款者生成还款账单(还款表 hks)
        * 每月应还钱=(本金+利息) 利率按百分比算,除以100
        */
        $amount = ($pro->money * $pro->rate/1200) + ($pro->money/$pro->hrange);

        $row = ['uid'=>$pro->uid,'pid'=>$pro->pid,'title'=>$pro->title];
        $row['amount'] = $amount;
        $row['status'] = 0;

        //循环产生每月还款记录
        $today = date('Y-m-d',time());//今天的日期
        for($i = 1; $i <= $pro->hrange; $i++) {
            $paydate = date('Y-m-d',strtotime("+ $i months"));//下一个月的日期
            $row['paydate'] = $paydate;
            DB::table('hks')->insert($row); //DB类可以直接添加一位数组到数据库
        }
        /**
        * 3. 为投资者生成收益账单(预期收益表 tasks)
        */
        $bid = Bid::where('pid',$pid)->get();//查询投资者信息
        // dd($bid);
        $data = [];
        $data['pid'] = $pid;
        $data['title'] = $pro->title;
        //收益截止日期
        $data['enddate'] = date('Y-m-d',strtotime("+ $pro->hrange months"));

        //循环为每位投资者生成 预收益信息
        foreach($bid as $b) {
            $data['uid'] = $b->uid;
            $data['amount'] = $b->money*$pro->rate/36500;
            DB::table('tasks')->insert($data);
        }
        // dd($data);
    }



     /*借款者 还款账单*/
     public function myzd() {
        $user = Auth::user();
        $hks = DB::table('hks')->where('uid',$user->uid)->paginate(5);
        return view('myzd',['hks'=>$hks]);
     }



     /*投资者,投资账单*/
     public function mytz() {
        $user = Auth::user();

        $bid = Bid::where('bids.uid',$user->uid)->whereIn('status',[1,2])->
                join('projects','bids.pid','=','projects.pid')->
                get(['bids.*','projects.status']);
        // dd($bid);
        return view('mytz',['bid'=>$bid]);
     }



     /*我的收益账单*/
     public function mysy() {
        $user = Auth::user();
        $grows = DB::table('grows')->where('uid',$user->uid)->orderBy('gid','desc')->get();
        return view('mysy',['grows'=>$grows]);
     }



     /*第三方支付*/
     public function pay(Request $req,$pid) {
        // dd($req->all());
        $pro = Pro::find($pid);
        
        /*判断购买的逻辑*/
        if($req->money > ($pro->money-$pro->recive)/100) {
            return redirect('/');//如果提交的钱大于项目剩余的钱,跳转到首页
        }
        
        $row = [];
        $row['v_amount'] = $req->money;
        $row['v_moneytype'] = 'CNY';
        $row['v_oid'] = date('YmdHis').mt_rand(1000,9999);
        $row['v_mid'] = '20272562';
        $row['v_url'] = 'http://aaa.com/touzi/' . $req->pid;  //支付完成后的回调地址
        // $row['v_url'] = 'http://aaa.com';
        $row['key'] ='%()#QOKFDLS:1*&U';
        $row['v_md5info'] = strtoupper(md5(implode('',$row)));
        
        return view('pay',$row);
     }


     /*验证码类*/
     public function captcha() {
        // $builder = new CaptchaBuilder($phrase);
        $builder = new CaptchaBuilder;
        $builder->build(); //生成验证码


        Session::put('code',strtoupper($builder->getPhrase()));

        header('Content-type: image/jpeg');
        $builder->output(); //直接输出
     }

}
